package com.mowh.multithreading.balking.host;

import java.util.concurrent.TimeoutException;

/**
 * @author mowh1gd
 * @create 2023/11/15 12:36
 */
public class Host {//Host是带状态(ready)的类
    private final long timeout; //guarded time
    private boolean ready = false;

    public Host(long timeout) {
        this.timeout = timeout;
    }
    public synchronized void setExecutable(boolean on) { //修改状态
        ready = on;
        notifyAll();
    }
    public synchronized void execute() throws TimeoutException, InterruptedException {
        long start = System.currentTimeMillis();
        while (!ready) { //检查状态后再执行，非守护条件下进入等待，等待超时则抛出异常
            long now = System.currentTimeMillis();
            long rest = timeout - (now - start);
            if (rest <= 0) {
                throw new TimeoutException("now - start = " + (now - start) + ", timeout = " + timeout);
            }
            wait(rest);// wait中设置guarded time
        }
        doExecute();//守护条件下执行
    }
    private void doExecute() {
        System.out.println(Thread.currentThread().getName() + " calls doExecute");
    }
}
